/*
 * @Author: gonglf
 * @Date: 2022-06-11 11:26:37
 * @Last Modified by:   gonglf
 * @Last Modified time: 2022-06-11 11:26:37
 */
package asynctask

//方法的注册和获取
import (
	"fmt"
	"sync"

	"gitee.com/distributed-asynchronous-task/tasks"
	"honnef.co/go/tools/config"
	// "honnef.co/go/tools/config"
)

type Server struct {
	config          *config.Config
	registeredTasks *sync.Map
	broker          brokersiface.Broker //这个是获取任务的
	// backend           backendsiface.Backend //这个存放执行的结果的
	// lock              lockiface.Lock
	// scheduler         *cron.Cron //这个是执行异步任务的
	// prePublishHandler func(*tasks.Signature) //这个是预发布
}

func NewServer(cnf *config.Config, brokerServer brokersiface.Broker) *Server {
	srv := &Server{
		config:          cnf,
		registeredTasks: new(sync.Map),
		broker:          brokerServer,
		// backend:         backendServer,
		// lock:            lock,
		// scheduler:       cron.New(),
	}

	// Run scheduler job
	// go srv.scheduler.Run()

	return srv
}

func (server *Server) RegisterTasks(namedTaskFuncs map[string]interface{}) error {
	for _, task := range namedTaskFuncs {
		if err := tasks.ValidateTask(task); err != nil {
			return err
		}
	}
	for k, v := range namedTaskFuncs {
		server.registeredTasks.Store(k, v)
	}
	// server.broker.SetRegisteredTaskNames(server.GetRegisteredTaskNames())
	return nil
}

func (server *Server) RegisterTask(name string, taskFunc interface{}) error {
	if err := tasks.ValidateTask(taskFunc); err != nil {
		return err
	}
	server.registeredTasks.Store(name, taskFunc)
	// server.broker.SetRegisteredTaskNames(server.GetRegisteredTaskNames())
	return nil
}

func (server *Server) IsTaskRegistered(name string) bool {
	_, ok := server.registeredTasks.Load(name)
	return ok
}

//获得func
func (server *Server) GetRegisteredTask(name string) (interface{}, error) {
	taskFunc, ok := server.registeredTasks.Load(name)
	if !ok {
		return nil, fmt.Errorf("task not registered error: %s", name)
	}
	return taskFunc, nil
}

func (server *Server) GetRegisteredTaskNames() []string {
	taskNames := make([]string, 0)

	server.registeredTasks.Range(func(key, value interface{}) bool {
		taskNames = append(taskNames, key.(string))
		return true
	})
	return taskNames
}
